package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.DiskBasedCache;
import com.bumptech.glide.Glide;
import com.gongpingjialoan.BuildConfig;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.RemindPriceChangeActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.data.CityData;
import com.gongpingjialoan.data.KCookie;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.PreferenceUtils;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.widget.ConfirmDialog;
import com.gongpingjialoan.widget.LoadingDialog;

import org.json.JSONObject;

import java.io.File;

/**
 * 设置界面   wang
 *
 * @author Administrator
 */
public class SettingActivity extends BaseActivity implements OnClickListener {
    private final int REQUEST_CITY_FRAGMENT = 1;
    private final int REQUEST_USER_CENTER = 99;
    private SettingActivity mySelf = this;
    private RelativeLayout city_layoutV;
    private TextView cityT;
    private CityData mCityData;
    private RelativeLayout clear_cache_layout = null;
    private View loginView;
    private RelativeLayout score_layoutV;
    private RelativeLayout ip_layoutV ,ed_user;
//            ed_password;
    private RelativeLayout price_change_layout, aboutRelativeLayout;
    private CheckBox mSwitchCompat;
    private NetDataJson pushNetDataJson;
    private UserManager mUserManager = null;

    private LoadingDialog loadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData =true;
        action = "my_settings";
        super.onCreate(savedInstanceState);
        mCityData = GPJApplication.getInstance().getCityData();
        setContentView(R.layout.activity_setting);

        mUserManager = new UserManager(mySelf);
        mUserManager = mUserManager.LoadUserInfo();

        cityT = (TextView) findViewById(R.id.city);
        cityT.setText(Utils.getCityName(this));
        loginView = findViewById(R.id.unlogin);
        city_layoutV = (RelativeLayout) findViewById(R.id.city_layout);
        setTitle("设置");
        clear_cache_layout = (RelativeLayout) findViewById(R.id.clear_cache_layout);
        clear_cache_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                StepMonitor.getInstance().addMonitor(new Monitor("click" , "clearCache" , System.currentTimeMillis() , 1f));
                DiskBasedCache diskBasedCache = new DiskBasedCache(new File(mySelf.getCacheDir(), "volley"));
                diskBasedCache.clear();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(SettingActivity.this).clearDiskCache();

                    }
                }).start();

                Toast.makeText(mySelf, "缓存已清理", Toast.LENGTH_SHORT).show();
            }
        });
        city_layoutV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "defaultCity", System.currentTimeMillis(), 1.0f));
                Intent cityit = new Intent();
                cityit.putExtra("needProvince", false);
                cityit.setClass(SettingActivity.this, CityActivity.class);
                startActivityForResult(cityit, REQUEST_CITY_FRAGMENT);
            }
        });

        ed_user = (RelativeLayout) findViewById(R.id.ed_user);
        ed_user.setOnClickListener(this);
//        ed_password = (RelativeLayout) findViewById(R.id.ed_password);
        aboutRelativeLayout = (RelativeLayout) findViewById(R.id.about_layout);
        score_layoutV = (RelativeLayout) findViewById(R.id.score_layout);
        price_change_layout = (RelativeLayout) findViewById(R.id.price_change_layout);
        mSwitchCompat = (CheckBox) findViewById(R.id.switch_id);
        score_layoutV.setOnClickListener(this);
        aboutRelativeLayout.setOnClickListener(this);
//        ed_password.setOnClickListener(this);
        if (GPJApplication.getInstance().isLogin()) {
            loginView.setVisibility(View.VISIBLE);
            ed_user.setVisibility(View.VISIBLE);
            findViewById(R.id.line).setVisibility(View.GONE);
        } else {
            loginView.setVisibility(View.GONE);
            ed_user.setVisibility(View.GONE);
            findViewById(R.id.line).setVisibility(View.VISIBLE);
        }

        if (GPJApplication.getInstance().accept_pushing) {
            mSwitchCompat.setChecked(true);
        } else {
            mSwitchCompat.setChecked(false);
        }

        pushNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(SettingActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
            }
        });
        pushNetDataJson.setUrl(API.switch_pushing);

        mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    pushNetDataJson.addParam("status", "open");
                    pushNetDataJson.request("post");
                    GPJApplication.getInstance().accept_pushing = true;
                } else {
                    pushNetDataJson.addParam("status", "close");
                    pushNetDataJson.request("post");
                    GPJApplication.getInstance().accept_pushing = false;
                }
            }
        });

        price_change_layout.setOnClickListener(this);


        ip_layoutV = (RelativeLayout) findViewById(R.id.idconfig);
        if (BuildConfig.LEO_DEBUG) {
            ip_layoutV.setVisibility(View.VISIBLE);
            ip_layoutV.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AppCompatDialog ad = new AppCompatDialog(SettingActivity.this, R.style.Dialog_Fullscreen);
                    ad.setContentView(R.layout.config);

                    String[] ds = {"http://api8.gongpingjia.com","http://api8.eyelee.cn" ,  "http://192.168.1.81:8000", "http://192.168.1.82:8000"};
                    //创建一个ArrayAdapter
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(SettingActivity.this,
                            android.R.layout.simple_dropdown_item_1line, ds);
                    final AutoCompleteTextView editText = (AutoCompleteTextView) ad.findViewById(R.id.ip);
                    editText.setAdapter(adapter);
                    editText.setThreshold(1);
                    Button button = (Button) ad.findViewById(R.id.button);
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String uri = editText.getText().toString();
                            SharedPreferencesUtil.put(SettingActivity.this, "domain", uri);
                            NetDataJson.SERVER_DOMAIN = uri;
                            ad.dismiss();
                            Toast.makeText(SettingActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    ad.show();

                }
            });
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    if (city != null) {
                        cityT.setText(city);
                        mCityData.mCurrentCity = city;
                        MainActivity.main.currentCity = city;
                        Utils.changeCity(city);
                        SharedPreferences sharedPreferences = getSharedPreferences("user_city", Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString("city", city);
                        edit.commit();

                        GPJApplication.getInstance().isChangeCity = true;
                        if (MainActivity.main != null) {
                            if (MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
                                MainActivity.main.assessmentFragment.changCity(city);
                            }
                            if (MainActivity.main.mRecomendDiscountFragment != null) {
                                MainActivity.main.mRecomendDiscountFragment.updateDiscountListData();
                            }
                            MainActivity.main.getNewCarActivity(city);
                        }

                    }
                    break;
                case REQUEST_USER_CENTER:
                    startActivity(new Intent(this, LoginActivity.class));
                    finish();
                    break;
            }

        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pushNetDataJson != null) {
            pushNetDataJson.cancelTask();
            pushNetDataJson = null;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == score_layoutV) {
            try {
                Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.gongpingjia"));
                viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(viewIntent);
            } catch (Exception e) {
                Toast.makeText(this, "尚未安装应用市场", Toast.LENGTH_SHORT).show();
            }
            StepMonitor.getInstance().addMonitor(new Monitor("click" , "rateGpj" , System.currentTimeMillis() , 1f));
        }
        if (v == price_change_layout) {
            Intent intent = new Intent(this, RemindPriceChangeActivity.class);
            startActivity(intent);
        }
        if (v == aboutRelativeLayout) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "aboutUs", System.currentTimeMillis(), 1f));
            startActivity(new Intent(this, AboutActivity.class));
        }else if(v == ed_user){
            Intent intent = new Intent(this, UserCenterActivity.class);
            intent.putExtra("from_setting" , true);
            startActivityForResult(intent, REQUEST_USER_CENTER);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }


    public void delete(View v) {

        ConfirmDialog dialog = new ConfirmDialog(mySelf, "确定退出该账号吗？", new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {

                    loadingDialog = new LoadingDialog(mySelf, "退出账号...");
                    loadingDialog.show();
                    mUserManager.Logout(new UserManager.OnLogoutResponse() {

                        @Override
                        public void onLogoutSuccess() {
                            loadingDialog.dismiss();
                            GPJApplication.getInstance().setIslogin(false);
                            PreferenceUtils mPreferenceUtils = new PreferenceUtils(mySelf);
                            mPreferenceUtils.clearObject(UserManager.class);
                            mPreferenceUtils.clearObject(KCookie.class);

                            if (MainActivity.main != null) {
                                if (MainActivity.main.mRecomendDiscountFragment != null)
                                    MainActivity.main.mRecomendDiscountFragment.updateDiscountListData();
                                if (MainActivity.main.mUserHomeFragment.isAdded()) {
                                    MainActivity.main.mUserHomeFragment.refresh();
                                }
                                if (MainActivity.main.assessmentFragment != null && MainActivity.main.assessmentFragment.isAdded()) {
                                    MainActivity.main.assessmentFragment.mMainRecomendView.getRecomendCars();
                                    MainActivity.main.assessmentFragment.mMainRecomendView.getBrowseCars();
                                }
                            }
                            setResult(RESULT_OK, new Intent());
                            mySelf.finish();
                        }

                        @Override
                        public void onLogoutError(String errorMessage) {
                            loadingDialog.dismiss();
                            Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
        dialog.show();
    }


}
